<template>
  <!-- <client-only> -->
  <div id="pageContainer">
    <div>
      <button id="prev" @click="onPrevPage()">
        上一页
      </button>
      <button id="next" @click="onNextPage()">
        下一页
      </button>
      &nbsp; &nbsp;
      <span>页码: <span id="page_num"/> / <span id="page_count"/></span>
    </div>
    <canvas id="the-canvas" @contextmenu="onNoContentMenu($event)" />
  </div>
  <!-- </client-only> -->
</template>

<script>
export default {
  name: "PdfViewer",
  props: { docPath: String },
  data() {
    return {
      PDFJS: require("pdfjs-dist/legacy/build/pdf"),
      pfdDoc: null,
      pageNum: 1,
      pageRendering: false,
      pageNumPending: null,
      scale: 1,
      canvas: null,
      ctx: null
    };
  },
  mounted() {
    this.PDFJS.GlobalWorkerOptions.workerSrc =
      "https://cdn.jsdelivr.net/npm/pdfjs-dist@2.9.359/build/pdf.worker.min.js";

    this.canvas = document.getElementById("the-canvas");
    this.ctx = this.canvas.getContext("2d");

    this.getPdf();
  },
  methods: {
    getPdf() {
      this.PDFJS.getDocument(this.docPath).promise.then(_pdfDoc => {
        this.pfdDoc = _pdfDoc;
        document.getElementById(
          "page_count"
        ).textContent = this.pfdDoc.numPages;

        this.renderPage(this.pageNum);
      });
    },

    renderPage(num) {
      this.pageRendering = true;

      this.pfdDoc.getPage(num).then(page => {
        const viewport = page.getViewport({ scale: this.scale });
        this.canvas.height = viewport.height;
        this.canvas.width = viewport.width;

        const renderContext = {
          canvasContext: this.ctx,
          viewport
        };
        const renderTask = page.render(renderContext);

        renderTask.promise.then(() => {
          this.pageRendering = false;
          if (this.pageNumPending !== null) {
            this.renderPage(this.pageNumPending);
            this.pageNumPending = null;
          }
        });
      });

      document.getElementById("page_num").textContent = num;
    },

    queueRenderPage(num) {
      if (this.pageRendering) {
        this.pageNumPending = num;
      } else {
        this.renderPage(num);
      }
    },

    onPrevPage() {
      if (this.pageNum <= 1) {
        return;
      }
      this.pageNum--;
      this.queueRenderPage(this.pageNum);
    },

    onNextPage() {
      if (this.pageNum >= this.pfdDoc.numPages) {
        return;
      }
      this.pageNum++;
      this.queueRenderPage(this.pageNum);
    },

    onNoContentMenu(event) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
};
</script>

<style>
#pageContainer {
  margin: auto;
  width: 80%;
}

div.page {
  display: inline-block;
}

#pageContainer span {
  color: #fff;
}
</style>
